//
//  MopubAdMangaer.m
//  HybidMediation
//
//  Created by jay Win on 2019/9/12.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "MopubAdMangaer.h"
#import "MoPub.h"

@interface MopubAdMangaer()<MPInterstitialAdControllerDelegate,MPRewardedVideoDelegate,MPAdViewDelegate>
@property(nonatomic,strong)MPAdView *bannerView;
@property(nonatomic,strong)MPInterstitialAdController *interstitial;
@end

@implementation MopubAdMangaer
#pragma mark   初始化
- (void)initAds:(void (^)(void))succeed{
    [self loadPlacementID];
    dispatch_async(dispatch_get_main_queue(), ^{
        MPMoPubConfiguration *config =[[MPMoPubConfiguration alloc]initWithAdUnitIdForAppInitialization:self.reward_id];
        if(self.debug){
            config.loggingLevel=MPBLogLevelDebug;
        }
        [[MoPub sharedInstance]initializeSdkWithConfiguration:config completion:^(){
            succeed();
            [self requestRewardVideo];
            [self requestInterstitial];
        }];
    });
}
- (void)agreeCOPPA{
    
}
- (void)agreeGDPR{
    
    
}
- (void)loadPlacementID{
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_banner_id"]){
        self.banner_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_banner_id"];
    }else{
        if([[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_banner_id"]==nil)
            NSLog(@"mopub_banner_id为空，请在AdsConfig文件中配置mopub_banner_id字段");
        self.banner_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_banner_id"];
    }
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_interstitial_id"]){
        self.interstitial_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_interstitial_id"];
     }else{
         if([[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_interstitial_id"]==nil)
              NSLog(@"mopub_interstitial_id为空，请在AdsConfig文件中配置mopub_interstitial_id字段");
         self.interstitial_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_interstitial_id"];
     }
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_rewardVideo_id"]){
        self.reward_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_pad_rewardVideo_id"];
     }else{
         if([[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_rewardVideo_id"]==nil)
             NSLog(@"mopub_rewardVideo_id为空，请在AdsConfig文件中配置mopub_rewardVideo_id字段");
         self.reward_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"mopub_rewardVideo_id"];
     }
}

- (void)showlog:(NSObject *)obj{
    if(self.debug)
    NSLog(@"====MOPUB=====%@",obj);
}

#pragma mark  banner
- (void)showBanner:(UIViewController *)rootViewController bannerContainner:(UIView *)containner{
    self.rootViewController=rootViewController;
    self.bannerContainer=containner;
    _bannerView= [[MPAdView alloc] initWithAdUnitId:self.banner_id size:iPad?MOPUB_LEADERBOARD_SIZE:MOPUB_BANNER_SIZE];
    [_bannerView startAutomaticallyRefreshingContents];
    _bannerView.delegate=self;
    [_bannerView loadAd];
    [self.delegate onBannerRequest];
}


- (void)showBanner:(UIViewController *)rootViewController bannerContainner:(UIView *)containner isTop:(BOOL)position{
    self.needFixBannerSize=YES;
    self.isBannerTop=position;
    [self showBanner:rootViewController bannerContainner:containner];
}

- (void)showBanner:(UIViewController *)rootViewController bannerUIContainer:(UIView *)container onImpressionEvent:(void (^)(void))onImpression{
    self.onBannerImpression=onImpression;
    [self showBanner:rootViewController bannerContainner:container];
}
- (void)hideBanner{
    if(_bannerView){
        [_bannerView stopAutomaticallyRefreshingContents];
        [_bannerView removeFromSuperview];
    }
    
}
#pragma mark  banner回调
- (UIViewController *)viewControllerForPresentingModalView {
    return self.rootViewController;
}

- (void)adViewDidLoadAd:(MPAdView *)view adSize:(CGSize)adSize{
    if(self.needFixBannerSize){
         if(IPhoneX){
            _bannerView.frame = CGRectMake((SCREENWIDTH -adSize.width) / 2,
                                           self.isBannerTop?44:SCREENHEIGHT - adSize.height-34,
                                           adSize.width,adSize.height);
        }else {
            _bannerView.frame = CGRectMake((SCREENWIDTH- adSize.width) / 2,
                                           self.isBannerTop?0:SCREENHEIGHT- adSize.height,
                                           adSize.width,adSize.height);
        }
    }
    [[self bannerContainer]addSubview:_bannerView];
    [self.delegate onBannerLoaded];
     [self.delegate onBannerImpression];
}
- (void)adView:(MPAdView *)view didFailToLoadAdWithError:(NSError *)error{
    if(error){
        [self.delegate onBanenrLoadedFailed:error.localizedDescription];
    }
}
- (void)willPresentModalViewForAd:(MPAdView *)view{
   
}
#pragma mark  插屏
- (void)requestInterstitial{
    if(self.isRequestingInterstitial)
        return;
   
    self.isRequestingInterstitial=YES;
    [self.delegate onInterstitialRequest];
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_interstitial=[MPInterstitialAdController interstitialAdControllerForAdUnitId:self.interstitial_id];
        self->_interstitial.delegate=self;
        [self->_interstitial loadAd];
    });
}

- (BOOL)hasInterstitial{
    if(_interstitial&&[_interstitial ready]){
        return YES;
    }else{
        [self requestInterstitial];
        return NO;
    }
}
- (void)showInterstitial:(UIViewController *)rootViewController{
    if(self.hasInterstitial){
         [self.delegate onInterstitialTrigger];
         [_interstitial showFromViewController:rootViewController];
    }else{
        [self showlog:@"插屏广告尚未准备好"];
    }
}

- (void)showInterstitial:(UIViewController *)rootViewController onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose{
    self.onVideoOpen=onOpen;
    self.onVideoClose=onClose;
    [self showInterstitial:rootViewController];
  
}
#pragma mark   插屏回调
- (void)interstitialDidLoadAd:(MPInterstitialAdController *)interstitial{
    self.isRequestingInterstitial=NO;
    [self showlog:@"插屏广告加载成功"];

    [self.delegate onInterstitialLoaded];
}
- (void)interstitialDidFailToLoadAd:(MPInterstitialAdController *)interstitial withError:(NSError *)error{
    self.isRequestingInterstitial=NO;
    if(error){
            [self.delegate onInterstitialLoadedFailed:error.localizedDescription];
       }
    if([KKADManager shareInstance].currentlyRecycleRequestInterstitialTimes<=[KKADManager shareInstance].maxRecycleRequestInterstitialTimes){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self requestInterstitial];
        });
    }else{
        [KKADManager shareInstance].currentlyRecycleRequestRewardVideoTimes=0;
    }
}
- (void)interstitialWillAppear:(MPInterstitialAdController *)interstitial{
    [self showlog:@"插屏即将打开"];
}
- (void)interstitialDidAppear:(MPInterstitialAdController *)interstitial{
    [self showlog:@"插屏打开"];
    [self.delegate onInterstitialOpen];
}
- (void)interstitialWillDisappear:(MPInterstitialAdController *)interstitial{
    [self showlog:@"插屏即将关闭"];
}
- (void)interstitialDidDisappear:(MPInterstitialAdController *)interstitial{
    [self showlog:@"插屏已经关闭"];
    [self.delegate onInterstitialClose];
    [self requestInterstitial];
}
- (void)interstitialDidReceiveTapEvent:(MPInterstitialAdController *)interstitial{
    [self showlog:@"插屏点击"];
    [self.delegate onInterstitialClick];
}

#pragma mark   激励
- (void)requestRewardVideo{
    if(self.isRequestingRewardVideo)
        return;
    self.completeRewardVideo=NO;
    self.isRequestingRewardVideo=YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [MPRewardedVideo setDelegate:self forAdUnitId:self.reward_id];
        [MPRewardedVideo loadRewardedVideoAdWithAdUnitID:self.reward_id withMediationSettings:nil];
    });
     [self.delegate onRewardVideoRequest];
}
- (BOOL)hasRewardVideo{
    if([MPRewardedVideo hasAdAvailableForAdUnitID:self.reward_id]){
        return  YES;
    }else{
        [self requestRewardVideo];
        return  NO;
    }
}
- (void)showRewardVideo:(UIViewController *)rootViewController{
    if(self.hasRewardVideo){
        [self.delegate onRewardVideoTrigger];
        [MPRewardedVideo presentRewardedVideoAdForAdUnitID:self.reward_id fromViewController:rootViewController withReward:nil];
    }else{
        [self showlog:@"激励广告尚未准备好"];
    }
}
- (void)showRewardVideo:(UIViewController *)rootViewController onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose onCompleteEvent:(void (^)(void))onComplete{
    self.onVideoOpen=onOpen;
    self.onVideoClose=onClose;
    self.onVideoComplete=onComplete;
    [self showRewardVideo:rootViewController];
}
#pragma mark   激励回调
- (void)rewardedVideoAdDidLoadForAdUnitID:(NSString *)adUnitID{
    [self showlog:@"激励加载成功"];
     self.isRequestingRewardVideo=NO;
    [self.delegate onRewardVideoLoaded];
}
- (void)rewardedVideoAdDidFailToLoadForAdUnitID:(NSString *)adUnitID error:(NSError *)error{
    self.isRequestingRewardVideo=NO;
    if(error){
         [self.delegate onRewardVideoLoadedFailed:error.localizedDescription];
    }
    if([KKADManager shareInstance].currentlyRecycleRequestRewardVideoTimes<[KKADManager shareInstance].maxRecycleRequestRewardVideoTimes){
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
              [self requestRewardVideo];
          });
        
    }else{
        [KKADManager shareInstance].currentlyRecycleRequestRewardVideoTimes=0;
    }

}
- (void)rewardedVideoAdWillAppearForAdUnitID:(NSString *)adUnitID{
    [self showlog:@"激励即将打开"];
}
- (void)rewardedVideoAdDidAppearForAdUnitID:(NSString *)adUnitID{
    [self showlog:@"激励已经打开"];
    if(self.onVideoOpen)
        self.onVideoOpen();
    [self.delegate onRewardVideoOpen];
}
- (void)rewardedVideoAdDidReceiveTapEventForAdUnitID:(NSString *)adUnitID{
    [self showlog:@"激励点击"];
    [self.delegate onRewardVideoClick];
}
- (void)rewardedVideoAdWillDisappearForAdUnitID:(NSString *)adUnitID{
    [self showlog:@"激励即将关闭"];
}
- (void)rewardedVideoAdDidDisappearForAdUnitID:(NSString *)adUnitID{
    if(self.completeRewardVideo){
        if(self.onVideoComplete)
            self.onVideoComplete();
        [self.delegate onRewardVideoComplete];
    }else{
        [self showlog:@"激励中途关闭"];
        if(self.onVideoClose)
            self.onVideoClose();
        [self.delegate onRewardVideoClose];
    }
    [self requestRewardVideo];
}

- (void)rewardedVideoAdDidFailToPlayForAdUnitID:(NSString *)adUnitID error:(NSError *)error{
    [self showlog:@"激励播放失败"];
    if(error){
         [self.delegate onRewardVideoPlayFailed:error.localizedDescription];
    }
}
- (void)rewardedVideoAdShouldRewardForAdUnitID:(NSString *)adUnitID reward:(MPRewardedVideoReward *)reward{
     [self showlog:@"激励发放奖励"];
     self.completeRewardVideo=YES;
}
#pragma mark   时时展示回调
- (void)mopubAd:(id<MPMoPubAd>)ad didTrackImpressionWithImpressionData:(MPImpressionData *)impressionData{
    [self parseImpressionDataToDict:impressionData];
}
-(void)parseImpressionDataToDict:(MPImpressionData *)impressionData{
    if (impressionData == nil)
    {
        return;
    }
    NSError *jsonSerializationError = nil;
    NSObject *impressionObject = [NSJSONSerialization JSONObjectWithData:impressionData.jsonRepresentation options:0 error:&jsonSerializationError];
    NSDictionary* dict = [impressionObject isKindOfClass:NSDictionary.class] ? (NSDictionary *)impressionObject : nil;
    if (dict == nil)
    {
        return ;
    }
    NSMutableDictionary *obj = [NSMutableDictionary dictionary];
    NSString *adFormat=[dict objectForKey:@"adunit_format"];
    [obj setObject:adFormat==nil?@"":adFormat forKey:AD_FORMAT];
    [obj setObject:self.idfa==nil?@"":self.idfa forKey:AD_IDFA];
    [obj setObject:[[NSUserDefaults standardUserDefaults]stringForKey:@"KK_AD_SOURCE"]==nil?@"unKnow":[[NSUserDefaults standardUserDefaults]stringForKey:@"KK_AD_SOURCE"]forKey:AD_USER_SOURCE];

    if([dict objectForKey:@"adunit_name"]){
        [obj setObject:[dict objectForKey:@"adunit_name"] forKey:AD_PLACEMENT_NAME];
    }
    if([dict objectForKey:@"network_name"]){
        [obj setObject:[dict objectForKey:@"network_name"] forKey:AD_NETWORK];
    }else{
        [obj setObject:@"unKonw_netWork" forKey:AD_NETWORK];
    }
    if([dict objectForKey:@"adgroup_name"]){
        [obj setObject:[dict objectForKey:@"adgroup_name"] forKey:AD_ITEM_NAME];
    }
    if([dict objectForKey:@"adgroup_type"]){
        [obj setObject:[dict objectForKey:@"adgroup_type"] forKey:AD_TYPE];
    }
    if([dict objectForKey:@"network_placement_id"]){
        [obj setObject:[dict objectForKey:@"network_placement_id"] forKey:AD_NETWORK_ID];
    }
    if([dict objectForKey:@"country"]){
        [obj setObject:[dict objectForKey:@"country"] forKey:AD_COUNTRY];
    }
    if([dict objectForKey:@"currency"] ){
        [obj setObject:[dict objectForKey:@"currency"] forKey:AD_CURRENCY];
    }
    if([dict objectForKey:@"precision"]){
        [obj setObject:[dict objectForKey:@"precision"] forKey:AD_PRECISION];
    }
    if([dict objectForKey:@"publisher_revenue"]){
        [obj setObject:[dict objectForKey:@"publisher_revenue"] forKey:AD_REVENUE];
    }
    [self showlog:[NSString stringWithFormat:@"Mopub时时展示数据:%@",obj.description]];
    [[KKAnalytics shareManager]logTKEvent:@"AD_IM" params: obj];
}
@end
